package com.wanghua.mall.order.webcontroller;

import com.wanghua.mall.order.service.OrderService;
import com.wanghua.mall.order.vo.OrderConfirmVo;
import com.wanghua.mall.order.vo.OrderSubmitResponseVo;
import com.wanghua.mall.order.vo.OrderSubmitVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;

/**
 * @author wanghua
 * @create 2021-09-07 21:55
 */
@Controller
public class OrderWebController {

    @Resource
    private OrderService orderService;


    /**
     * 前往订单结算页面
     *
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        model.addAttribute("OrderConfirmData", orderConfirmVo);
        return "confirm";
    }


    /**
     * 订单提交
     *
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes) {
        System.out.println(orderSubmitVo);
        OrderSubmitResponseVo orderSubmitResponseVo = orderService.submitOrder(orderSubmitVo);
        //下单成功来到支付选择页
        //下单失败回到订单确认页重新确定订单信息
        if (orderSubmitResponseVo.getCode() == 0) {
            model.addAttribute("orderSubmitResponse", orderSubmitResponseVo);
            return "pay";

        } else {
            String msg = "下单失败";
            switch (orderSubmitResponseVo.getCode()) {
                case 1:
                    msg += "令牌订单信息过期，请刷新再次提交";
                    break;
                case 2:
                    msg += "订单商品价格发生变化，请确认后再次提交";
                    break;
                case 3:
                    msg += "库存锁定失败，商品库存不足";
                    break;
            }
            redirectAttributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.mall.com/toTrade";
        }
    }
}
